package com.ylr.basic.framework.service.impl;

import com.ylr.basic.framework.entity.IpAddressEntity;
import com.ylr.basic.framework.entity.RequestLogEntity;
import com.ylr.basic.framework.service.IpAddressService;
import com.ylr.base.common.po.RequestLogPo;
import com.ylr.base.framework.service.SnowflakeService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ylr.basic.framework.mapper.RequestLogMapper;
import com.ylr.basic.framework.service.RequestLogService;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-04-28 22:24:10
 * className: RequestLogServiceImpl 请求日志服务接口实现类
 * version: 1.0
 * description:
 */
@Service("requestLogService")
@AllArgsConstructor
public class RequestLogServiceImpl extends ServiceImpl<RequestLogMapper, RequestLogEntity> implements RequestLogService {

    private static final Logger log = LoggerFactory.getLogger(RequestLogServiceImpl.class);

    private final SnowflakeService snowflakeService;

    private final IpAddressService ipAddressService;

    @Override
    public void saveRequestLog(RequestLogPo requestLogPo) {

        String requestIp = requestLogPo.getRequestIp();
        // 获取ip地址对应的真实地址
        String address = StringUtils.EMPTY;
        try {
            IpAddressEntity ipAddress = ipAddressService.getIpAddress(requestIp);
            address = ipAddress.getRequestAddress();
        } catch (Exception e) {
            log.error("获取ip对应的真实地址失败。requestIp={}", requestIp);
        }

        RequestLogEntity requestLog = new RequestLogEntity();
        // 属性值赋值
        BeanUtils.copyProperties(requestLogPo, requestLog);
        requestLog.setId(snowflakeService.getId())
                .setAddress(address)
                .setCreateTime(new Date());
        // 插入数据
        baseMapper.insert(requestLog);
        log.info("请求日志落库完成");
    }
}